package hn.sigit.model.ladm.special;

import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.*;

import java.sql.*;
import java.io.*;

public class RationalUserType implements CompositeUserType {
	@Override
	public String[] getPropertyNames() {
		return new String[] {"nominator", "denominator"};
	}

	@Override
	public Type[] getPropertyTypes() {
		return new Type[] {Hibernate.INTEGER, Hibernate.INTEGER};
	}

	@Override
	public Object getPropertyValue(Object component, int property)
			throws HibernateException {
		Rational rational = (Rational)component;
		if (property == 0)
			return rational.getNumerator();
		else
			return rational.getDenominator();
	}

	@Override
	public void setPropertyValue(Object component, int property, Object value)
			throws HibernateException {
		throw new UnsupportedOperationException();
	}

	
	@Override
	public Object nullSafeGet(ResultSet resultSet, String[] names,
			SessionImplementor session, Object owner)
			throws HibernateException, SQLException {
		int numerator = resultSet.getInt(names[0]);
		if (resultSet.wasNull()) return null;
		
		int denominator = resultSet.getInt(names[1]);
		if (resultSet.wasNull()) return null;


		return new Rational(numerator, denominator);
	}

	@Override
	public void nullSafeSet(PreparedStatement statement, Object value, int index,
			SessionImplementor session) throws HibernateException, SQLException {
		if (value == null) {
			statement.setNull(index, Hibernate.INTEGER.sqlType());
			statement.setNull(index+1, Hibernate.INTEGER.sqlType());
		}
		else {
			Rational rational = (Rational)value;
			statement.setInt(index, rational.getNumerator());
			statement.setInt(index+1, rational.getDenominator());
		}
	}

	@Override
	public Serializable disassemble(Object value, SessionImplementor session)
			throws HibernateException {
		return (Serializable)value;
	}

	@Override
	public Object assemble(Serializable cached, SessionImplementor session,
			Object owner) throws HibernateException {
		return cached;
	}

	@Override
	public Object replace(Object original, Object target,
			SessionImplementor session, Object owner) throws HibernateException {
		return original;
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y) return true;
		if (x == null || y == null) return false;
		return x.equals(y);
	}
	
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}
	
	public Object deepCopy(Object aObject) throws HibernateException {
		return aObject;
	}
	
	public boolean isMutable() {
		return false;
	}
	
	public Class returnedClass() {
		return Rational.class;
	}
}
